﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Text.RegularExpressions;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Globalization;

namespace SPHelper
{
	public class Html
	{
		/// <summary>
		/// Highlight keywords, esp helpful with search results
		/// </summary>
		/// <param name="textToHighlight"></param>
		/// <param name="keywords"></param>
		/// <param name="startHtmlTag"></param>
		/// <param name="endHtmlTag"></param>
		/// <returns></returns>
		public static string HighlightKeywords(string textToHighlight, string[] keywords, 
			string startHtmlTag, string endHtmlTag)
		{
			// init
			if (string.IsNullOrEmpty(textToHighlight)) { return textToHighlight; }
			if (string.IsNullOrEmpty(startHtmlTag) && string.IsNullOrEmpty(endHtmlTag))
			{
				SPHelper.Log.WriteError("45wi67rot8yufgh", "Must pass start and end html tags to highlight");
				return textToHighlight;
			}
			if (keywords == null || keywords.Length == 0) { return textToHighlight; }


			foreach (string keyword in keywords)
			{
				if (!string.IsNullOrEmpty(keyword) && keyword.Trim() != string.Empty)
				{
					textToHighlight = Regex.Replace(textToHighlight, Regex.Escape(keyword),
						startHtmlTag + keyword + endHtmlTag, RegexOptions.IgnoreCase | RegexOptions.Singleline);
				}
			}
			return textToHighlight;
		}


		/// <summary>
		/// Register javascript for page if js file not already in use
		/// </summary>
		/// <param name="page"></param>
		/// <param name="scriptUrl"></param>
		public static void RegisterJavascript(System.Web.UI.Page page, string scriptUrl)
		{
			if (!page.ClientScript.IsClientScriptIncludeRegistered(scriptUrl))
			{
				page.ClientScript.RegisterClientScriptInclude(scriptUrl, scriptUrl);
			}
		}

		/// <summary>
		/// Register css for page if not already exist
		/// </summary>
		/// <param name="page"></param>
		/// <param name="cssUrl"></param>
		public static void RegisterCss(System.Web.UI.Page page, string cssUrl)
		{
			// create css link control
			var cssLink = new HtmlLink { Href = cssUrl };
			cssLink.Attributes.Add("rel", "stylesheet");

			// add css if doesn't already exist
			if (!page.Header.Controls.Contains(cssLink)) { page.Header.Controls.Add(cssLink); }
		}

		public enum DateDisplay
		{
			Number,
			Fullname,
			Abbreviated,
		}

		public static Dictionary<int, string> GetMonths(DateDisplay monthDisplay)
		{
			Dictionary<int, string> months = new Dictionary<int, string>();
			try
			{
				for (int i = 1; i < 13; i++)
				{
					if (monthDisplay == DateDisplay.Abbreviated)
					{
						months.Add(i, CultureInfo.CurrentCulture.DateTimeFormat.GetAbbreviatedMonthName(i));
					}
					else if (monthDisplay == DateDisplay.Fullname)
					{
						months.Add(i, CultureInfo.CurrentUICulture.DateTimeFormat.GetMonthName(i));
					}
					else if (monthDisplay == DateDisplay.Number)
					{
						months.Add(i, i.ToString());
					}
					else
					{
						throw new Exception("Unknown date display option: " + monthDisplay.ToString());
					}
				}
			}
			catch (Exception ex)
			{
				Log.WriteError("dzsrgfgfddryssry", ex);
			}
			return months;
		}

		public static int GetDaysInMonth(int month, int year)
		{
			return System.DateTime.DaysInMonth(year, month);
		}


		public static string Pagination(string url, int pageNumber, int pageSize, int totalItems, string paginationLinkClass)
		{
			string o = null;
			try
			{
				// init
				if (pageNumber == 0) { pageNumber = 1; }
				if (string.IsNullOrEmpty(url) && HttpContext.Current != null && HttpContext.Current.Request != null) 
				{ url = HttpContext.Current.Request.Url.ToString(); }
				if (pageNumber < 0 || pageSize < 0 || totalItems < 0)
				{
					throw new Exception("Neither page number, page size, or total items can be less than 0");
				}
				double ceiling = 0;
				if (pageSize > 0) { ceiling = Math.Ceiling(((Double)totalItems / pageSize)); }
				if (!string.IsNullOrEmpty(paginationLinkClass)) { paginationLinkClass = " class='" + paginationLinkClass + "'"; }

				if (totalItems != 0 && ceiling > 1) 
				{
					// pagenumber separator
					var pageNumberSeparator = " ";
					if (ceiling < 21) { pageNumberSeparator = " &nbsp; "; }

					// format url base
					if (string.IsNullOrEmpty(url)) { url = "?"; }
					else if (url.ToLower().Contains("page=")) 
					{ url = url.Substring(0, url.ToLower().LastIndexOf("page=") - 1); }
					
					// append separator
					if (!url.Contains("?")) { url += "?"; }
					else if (url.Substring(url.Length-2,1) != "&") { url += "&"; }
					// append page reference
					url += "Page=";

					// previous link
					if (pageNumber > 1)
					{
						o += string.Format("<a href='{0}{1}' title='Previous Page'{2}>&lt; PREVIOUS</a>{3}", 
							url, pageNumber - 1, paginationLinkClass, pageNumberSeparator);
					}

					// all pages in between
					for (int i = 1; i <= ceiling; i++)
					{
						if (i == pageNumber)
						{
							// current page
							o += i.ToString() + pageNumberSeparator;
						}
						else
						{
							o += string.Format("<a href='{0}{1}' title='Page {1}'{2}>{1}</a>{3}", 
								url, i, paginationLinkClass, pageNumberSeparator);
						}
					}

					// next link
					if (ceiling > 1 && pageNumber < ceiling)
					{
						o += string.Format("<a href='{0}{1}' title='Next Page'{2}>NEXT &gt;</a>", 
							url, pageNumber + 1, paginationLinkClass);
					}

					// make bold?
					if (ceiling < 21) { o = "<div style='font-weight:bold;'>" + o + "</div>"; }
				}
			}
			catch (Exception ex)
			{
				Log.WriteError("dfgfgtddusdrrsdrtrdy", ex);
			}
			return o;
		}

		public static string Pagination(string url, int pageNumber, int pageSize, int totalItems)
		{
			// call original
			return Pagination(url, pageNumber, pageSize, totalItems, null);
		}

		/// <summary>
		/// Find urls and email addresses in plain text and convert into links
		/// http://weblogs.asp.net/farazshahkhan/archive/2008/08/09/regex-to-find-url-within-text-and-make-them-as-link.aspx
		/// </summary>
		/// <param name="plainText"></param>
		/// <param name="isLinkifyUrl"></param>
		/// <param name="isLinkifyEmail"></param>
		/// <returns></returns>
		public static string LinkifyText(string plainText, bool isLinkifyUrl, bool isLinkifyEmail)
		{
			try
			{
				if (!string.IsNullOrEmpty(plainText))
				{
					if (isLinkifyUrl)
					{
						plainText = Regex.Replace(plainText, @"(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&amp;:/~\+#]*[\w\-\@?^=%&amp;/~\+#])",
							delegate(Match m) { return string.Format("<a href=\"{0}\">{0}</a>", m.ToString()); });
					}
					if (isLinkifyEmail)
					{
						plainText = Regex.Replace(plainText, @"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*",
							delegate(Match m) { return string.Format("<a href=\"mailto:{0}\">{0}</a>", m.ToString()); });
					}
				}
			}
			catch (Exception ex)
			{
				Log.WriteError("fgthyjghgjfdfthgnbcf", ex);
			}
			return plainText;
		}

		//public static string CreateHierarchicalList(List<KeyValuePair<string, int>> listElements, string ulStartTag,
		//    Dictionary<int, string> stylesByLevel)
		//{
		//    var o = new StringBuilder();
		//    try
		//    {
		//        if (listElements != null)
		//        {
		//            int previousDepth = -1;
		//            int numUL = 0;
		//            foreach (var row in listElements)
		//            {
		//                int currentLevel = row.Value;
		//                var style = string.Empty;
		//                if (stylesByLevel != null && stylesByLevel.ContainsKey(currentLevel))
		//                {
		//                    style = " style='" + stylesByLevel[currentLevel] + "'";
		//                }

		//                if (previousDepth < currentLevel)
		//                {
		//                    if (currentLevel == 0)
		//                    {
		//                        o.Append(ulStartTag);
		//                        o.AppendFormat("<li{0}>{1}", style, row.Key);
		//                    }
		//                    else
		//                    {
		//                        o.Append("<ul>");
		//                        if (currentLevel == 1)
		//                        {
		//                            o.AppendFormat("<li{0}>{1}", style, row.Key);
		//                        }
		//                        else
		//                        {
		//                            o.AppendFormat("<li{0}>{1}", style, row.Key);
		//                        }
		//                    }
		//                    numUL++;
		//                }
		//                else if (previousDepth > currentLevel)
		//                {
		//                    //output.Append("</li></ul></li>");
		//                    o.Append("</li>");
		//                    for (int i = previousDepth; i > currentLevel; i--)
		//                    {
		//                        o.Append("</ul></li>");
		//                    }

		//                    if (currentLevel == 1)
		//                    {
		//                        o.AppendFormat("<li{0}>{1}", style, row.Key);
		//                    }
		//                    else
		//                    {
		//                        o.AppendFormat("<li{0}>{1}", style, row.Key);
		//                    }
		//                    numUL--;
		//                }
		//                else if (previousDepth > -1)
		//                {
		//                    o.Append("</li>");
		//                    o.AppendFormat("<li{0}>{1}", style, row.Key);
		//                }
		//                previousDepth = currentLevel;
		//            }

		//            for (int i = 1; i <= numUL + 1; i++)
		//            {
		//                o.Append("</li></ul>");
		//            }

		//        } // list elements passed not null
		//    }
		//    catch (Exception ex)
		//    {
		//        SPHelper.Log.WriteError("ew546ui7uetdfhdfsdsfdstr", ex);
		//    }
		//    return o.ToString();
		//}
	
	
	} // html namespace
}
